import { createRouter, createWebHistory } from 'vue-router'
import Login from './views/user/Login.vue'
import PhoneLogin from './views/user/PhoneLogin.vue'
import Forget from './views/user/Forget.vue'
// import Register from './views/user/Register.vue'
import PostList from './views/current/postList.vue'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import { useUserStore } from '@/store/modules/user'
import { useAgentStore } from '@/store/modules/agent'
import gzStorageWrapper from '@/utils/gzStorageWrapper'
import { generatorDynamicRouter } from '@/router/generator-routers'
import { setRouter } from '@/utils/routerUtils.js'
import basiclayout from './layouts/BasicLayout.vue'

NProgress.configure({ showSpinner: false })


const rootRoute: any = [
  { name: 'login', path: '/proxy/login', component: Login },
  { name: 'phoneLogin', path: '/phoneLogin', component: PhoneLogin },
  { name: 'forget', path: '/forget', component: Forget },
  // { name: 'register', path: '/register', component: Register },
  // {
  //   path: '/',
  //   component: basiclayout,
  //   children: [
  //     {
  //       path: 'postList',
  //       component: PostList
  //     }
  //   ]
  // }
]

const router = createRouter({
  history: createWebHistory(),
  routes: rootRoute
})

// 路由守卫
const allowList = ['login', 'register', 'registerResult', 'forget', 'phoneLogin'] // no redirect allowList
const loginRoutePath = '/proxy/login'

// 路由守卫 // eslint-disable-next-line @typescript-eslint/no-explicit-any
router.beforeEach((to: any, from, next) => {
  NProgress.start()

  // 如果在免登录页面则直接放行
  if (allowList.includes(to.name)) {
    // 免登录
    if (loginRoutePath === to.path && to.query && to.query.Itoken) {
      useUserStore().putToken(to.query.Itoken)
      useUserStore().setIsFreeLogin(true)
      to.query = undefined
      to.fullPath = loginRoutePath
      to.href = loginRoutePath
    }

    // 在免登录名单，直接进入
    next()
    NProgress.done()
    return false
  }

  // 不包含Token 则直接跳转到登录页面
  if (!gzStorageWrapper.getToken()) {
    next({ path: loginRoutePath, query: { redirect: to.fullPath } })
    NProgress.done()
    return false
  }
  // 以下为包含Token的情况
  // 如果用户信息不存在， 则重新获取 [用户登录成功 & 强制刷新浏览器时 会执行该函数]
  if (!useUserStore().userInfo.sysUserId) {
    useUserStore().refUserInfo().then(() => {
      // 刷新平台配置
      useAgentStore().initAgentStore()
      if(useUserStore().getIsFreeLogin()){
        useUserStore().clearFreeLogin()
      }
      generatorDynamicRouter().then((resRouter: any) => {
        //增加rootRouter
        router.addRoute(resRouter[0])

        // https://ask.csdn.net/questions/7419202, 解决跳转白屏的问题
        if (to.matched.length == 0) {
          router.push(to.path)
        }
      })
    })

  } else {
    next()
    return false
  }
})

// 之后处理
router.afterEach(() => {
  NProgress.done()
})

setRouter(router)

export default router
